// pages/webChat/webChat.js
const emoji = require('../../util/emoji.js')
var service_common = require("../../service/common.js");
const websocket = require('../../util/websocket.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    input: '',
    version: "1.5.0",
    search: '',
    more_style: false,
    allLoaded: false,
    page: 1,
    before_id: "",
    list: [],
    newsMsg: {},
    userInfo: {},
    otherInfo: {},
    toIndex: "",
    emoji: [],
    ID: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    wx.setNavigationBarTitle({
      title: options.title_name
    })
    console.log(wx.getStorageSync('p2'))
    this.setData({
      emoji: emoji.emoji,
      userInfo: {
        appid: getApp().globalData.imID,
        type: 'login',
        uid: wx.getStorageSync('userInfo').openid,
        uid_name: wx.getStorageSync('userInfo').nickname,
        uid_head: wx.getStorageSync('userInfo').src
      },
      otherInfo: {
        "appid": getApp().globalData.imID,
        "type": "login",
        "uid": wx.getStorageSync('p2').uid,
        "uid_head": wx.getStorageSync('p2').uid_head,
        "uid_name": wx.getStorageSync('p2').name
      }
    })
    this.get_message_list()
    this.init()
  },
  // 隐藏表情
  displayMore: function() {
    this.setData({
      more_style: false,
    })
    setTimeout(() => {
      this.setData({
        toIndex: this.data.ID
      })
    }, 500)
  },
  // 上传图片
  getPic: function() {
    var that = this
    this.setData({
      more_style: false,
    })
    setTimeout(() => {
      this.setData({
        toIndex: this.data.ID
      })
    }, 500)
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: service_common.getUrl("user.uploadimage"),
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            version: getApp().globalData.version
          },
          success(res) {
            var ress = JSON.parse(res.data)
            console.log(ress)
            if (ress.code == 0) {
              that.sendMessage('image', ress.data)
            }
          }
        })
      }
    })
  },
  // 获取输入数据
  setMessage: function(e) {
    this.setData({
      input: e.detail.value
    })
  },
  // 设置聊天窗口高度
  setStyle: function() {
    this.setData({
      more_style: !this.data.more_style,
    })
    setTimeout(() => {
      this.setData({
        toIndex: this.data.ID
      })
    }, 500)
  },
  emojitext: function(e) {
    this.data.input += e.currentTarget.dataset.text
    this.setData({
      input: this.data.input
    })
  },
  // ws连接
  init: function() {
    // 监听消息回调
    getApp().socketEven = (res) => {
      if (res.type == "login_back") { //登录成功后的回调
        this.get_message_list()
      } else if (res.type == 'getMessageList_back') { //获取消息
        if (res.data.length != 0) {
          if (this.data.page == 1) {
            this.setData({
              ID: "a" + res.data[res.data.length - 1].id
            })
          }
          this.data.page += 1
          res.data[res.data.length - 1].ID = "a" + res.data[res.data.length - 1].id
          this.setData({
            list: res.data.concat(this.data.list),
            before_id: res.data[0].id,
            page: this.data.page,
            toIndex: "a" + res.data[res.data.length - 1].id
          })
        }
      } else if (res.type == 'single_chat_back') {
        if (res.uid == this.data.otherInfo.uid) {
          res.ID = 'a' + this.data.list.length
          this.data.list[this.data.list.length] = res
          this.setData({
            list: this.data.list,
            toIndex: res.ID
          })
          websocket.send({
            "appid": getApp().globalData.imID,
            "type": "update_read",
            "uid": wx.getStorageSync('userInfo').openid,
            "ids": res.message_id
          })
        }
      }
    }
  },
  // 滑动到顶部
  isTop: function() {
    this.get_message_list()
  },
  // 获取消息列表
  get_message_list: function() {
    websocket.send({
      "appid": getApp().globalData.imID,
      "type": "get_message_list",
      "uid": this.data.userInfo.uid,
      "to_uid": this.data.otherInfo.uid,
      "p": this.data.page, //页数
      "ps": "10",
      "before_id": this.data.before_id
    })
  },
  sendm: function(e) {
    if (this.data.input.replace('/(^/s *)| (/s*$)/g', "") == ""){

    }else{
      this.sendMessage(e.currentTarget.dataset.type)
    }
    
  },
  // 图片预览
  previewImage: function(e) {
    wx.setStorageSync('ishide', false)
    wx.previewImage({
      current: e.currentTarget.dataset.image,
      urls: [e.currentTarget.dataset.image]
    })
  },
  /**
   * 发送消息，type：消息类型
   */
  sendMessage: function(types, imgUrl) {

    if (types == "text") {
      if (this.data.input.replace('/(^/s *)| (/s*$)/g', "") == "") {} else {
        var messageData = {
          "appid": getApp().globalData.imID,
          "type": "single_chat",
          "uid": this.data.userInfo.uid,
          "to_uid": this.data.otherInfo.uid,
          "to_head": this.data.otherInfo.uid_head,
          "to_name": this.data.otherInfo.uid_name,
          "message_type": "text",
          "message": this.data.input,
          "ID": "a" + this.data.list.length
        }
      }
    } else {
      var messageData = {
        "appid": getApp().globalData.imID,
        "type": "single_chat",
        "uid": this.data.userInfo.uid,
        "to_uid": this.data.otherInfo.uid,
        "to_head": this.data.otherInfo.uid_head,
        "to_name": this.data.otherInfo.uid_name,
        "message_type": "image",
        "message": imgUrl,
        "ID": "a" + this.data.list.length
      }
    }

    this.data.list[this.data.list.length] = messageData
    this.setData({
      list: this.data.list,
      input: '',
      ID: messageData.ID
    })
    websocket.send(messageData)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.setStorageSync('ishide', true)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    // if (wx.getStorageSync('ishide')){
    //   // wx.closeSocket()
    //   wx.switchTab({
    //     url: '/pages/index/index',
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    this.setData({
      otherInfo:{}
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})